package org.budo.poi.doc;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.ss.usermodel.Sheet;
import org.budo.poi.AbstractWorkbook;

import com.lowagie.text.Document;
import com.lowagie.text.Table;
import com.lowagie.text.rtf.RtfWriter2;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 * @see org.apache.poi.hwpf.HWPFDocument
 */
@Slf4j
public class DocWorkbook extends AbstractWorkbook {
    @Override
    public Sheet createSheet(String sheetname) {
        DocSheet sheet = new DocSheet(sheetname);
        this.getSheets().put(sheetname, sheet);
        return sheet;
    }

    @Override
    public void write(OutputStream outputStream) throws IOException {
        try {
            this.writeDocument(outputStream);
        } catch (Throwable e) {
            log.error("#33 e=" + e);
            throw new RuntimeException(e);
        }
    }

    private void writeDocument(OutputStream outputStream) throws Throwable {
        Sheet sheet = this.getSheetAt(0);

        int firstRow = sheet.getFirstRowNum();
        int lastRow = sheet.getLastRowNum();

        short firstCell = sheet.getRow(0).getFirstCellNum();
        short lastCell = sheet.getRow(0).getLastCellNum();

        Table table = new Table(lastCell + 1, lastRow);
        for (int i = firstRow; i < lastRow; i++) {
            for (int j = firstCell; j <= lastCell; j++) {
                String cellValue = sheet.getRow(i).getCell(j).getStringCellValue();
                table.addCell(cellValue);
            }
        }

        Document document = new Document();
        RtfWriter2.getInstance(document, outputStream);
        document.open();
        document.add(table);
        document.close();
    }
}